package fms.acarsMsgProcessUtil;

import fms.util.ObjectUtil;

/**
 * Created with IntelliJ IDEA.
 * To change this template use File | Settings | File Templates.
 */
public class RawDatagram {
    private String raw;
    //private String header;
    //private String body;

    /// <summary>
    /// 原始报文中报头与正文分隔符号
    /// </summary>
    public static final String SplitSymbol = "-  ";
    private static final String FreeTextFlag = "\r\n-  ";

    /// <summary>
    /// 报文结束符
    /// </summary>
    // System.out.println("-" + Integer.valueOf(EndSymbol) + "+");
    public static final char EndSymbol = new Character((char) 3);


    /// <summary>
    /// 得到原始报文中的报头部分
    /// </summary>
    /// <param name="msg">原始报文</param>
    /// <returns></returns>
    public static String GetHeader(String msg) {
        if (ObjectUtil.isBlank(msg)) {
            return "";
//            throw new ArgumentNullException("报头字符串不能为空");
        }

        int position = msg.indexOf(FreeTextFlag);
        if (position > 0) {
            return msg.substring(0, position + 2);
        }

        position = msg.indexOf(EndSymbol);
        if (position > 0) {
            return msg.substring(0, position);
        }

        return msg;
    }

    /// <summary>
    /// 得到原始报文中的正文部分
    /// </summary>
    /// <param name="msg"></param>
    public static String GetBody(String msg) {
//        System.out.println("\n\nGetBody:\n\n");
        int positionBegin = msg.indexOf(FreeTextFlag);
        int positionEnd = msg.indexOf(EndSymbol);
//        System.out.println("\n\nGetBody-position:\n\n" + position);
        if (positionBegin >= 2) {
            return msg.substring(positionBegin + 5, positionEnd + 1);
        }
        return "";
    }

    /// <summary>
    /// 将原始报文中的头与正文部分合并
    /// </summary>
    /// <param name="header">原始报文的头部字符串</param>
    /// <param name="body">原始报文的正文部分字符串</param>
    /// <returns>完整的620格式报文</returns>
    public static String Combine(String header, String body) throws Exception {
        String result = header;

        if (ObjectUtil.isBlank(header)) {
//            return "";
//            throw new ArgumentNullException("报头字符串不能为空");
            throw new Exception("报头字符串不能为空");
        }
        int index = header.indexOf(EndSymbol);

        if (index > -1) {
            result = header.substring(0, index);
        }

        if (!ObjectUtil.isBlank(body)) {
            if (body.indexOf(EndSymbol) > 0) {
                result = result + SplitSymbol + body;
            } else {
                result = result + SplitSymbol + body + EndSymbol;
            }
        } else {
            result = result + EndSymbol;
        }

        return result;
    }
}
